package com.asiainfo.ncrm.xtnfc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;

import com.asiainfo.ncrm.R;
import com.asiainfo.ncrm.nfc.FileOperationsJava;
import com.asiainfo.ncrm.nfc.IdCard_Bean;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.senter.helper.ConsantHelper;
import cn.com.senter.helper.ShareReferenceSaver;
//import cn.com.senter.updatable.model.IdentityCardZ;
import cn.com.senter.model.IdentityCardZ;
import cn.com.senter.sdkdefault.helper.Error;

public class XTNFCActivity extends Activity {

	private final static String SERVER_KEY = "CN.COM.SENTER.SERVER_KEY";
	private final static String PORT_KEY = "CN.COM.SENTER.PORT_KEY";
	private TextView tv_info;
	private TextView nameTextView;
	private TextView sexTextView;
	private TextView folkTextView;
	private TextView birthTextView;
	private TextView addrTextView;
	private TextView codeTextView;
	private TextView policyTextView;
	private TextView validDateTextView;
	private TextView dnTextView;
	private ImageView photoView;
	private TextView samidTextView;
	
	
	private Button buttonNFC, buttonOTG,buttonBT,btnSure;
	private TextView readsamtype;

	private String server_address;
	private int server_port;
	public static Handler uiHandler;

	private NFCReaderHelper mNFCReaderHelper;

	private AsyncTask<Void, Void, String> nfcTask = null;
	
	
    private PendingIntent pendingIntent;
    private IntentFilter[] intentFilters;
	
	//----蓝牙功能有关的变量----
    private BluetoothAdapter mBluetoothAdapter = null;			///蓝牙适配器
	BluetoothDevice device;							//蓝牙设备  需要传递给底层接口的变量
	
	String resultBean="";

	@Override
	protected void onNewIntent(Intent intent) {
		Log.e("MainActivity", "NFC 返回调用 onNewIntent");
		super.onNewIntent(intent);
		if (NFCReaderHelper.isNFC(intent)) {
			Log.e("MainActivity", "返回的intent可用");

			if (nfcTask == null) {
				nfcTask = new NFCReadTask(intent).executeOnExecutor(Executors
						.newCachedThreadPool());
			}
		} else {
			Log.e("MainActivity", "返回的intent不可用");
		}
//		readCardNFC();
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cloud);
		uiHandler = new MyHandler(this);
		
		///-----蓝牙屏蔽掉-----
//		 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//		 if (mBluetoothAdapter == null) {
//	            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
//	            finish();
//	            return;
//	     }
		
		initViews();
		initShareReference();
//		readCardNFC();

	}

	
	 @Override
   public void onStart() {
       super.onStart();
       Log.e("Main", "++ ON START ++");

       // If BT is not on, request that it be enabled.
       // setupChat() will then be called during onActivityResult
//       if (!mBluetoothAdapter.isEnabled()) {
//           Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//           startActivityForResult(enableIntent, 2);
//       // Otherwise, setup the chat session
//       }
//       else
//       {
//       		//此处应添加一个toast提示用户打开蓝牙功能---
//       }
       
       
       
   }
	 @Override
	 public void onStop ()
	 {
		 super.onStop();
	 }
	 
	 @Override
	 public void onPause()
	 {
		 super.onPause();
	 }
	 
	    private static final int REQUEST_CONNECT_DEVICE = 1;
	    private static final int REQUEST_ENABLE_BT = 2;
	    private static final int REQUEST_PREF_SETTING = 3;
	    private static final int REQUEST_DISCONNECT_DEVICE =  4;
	    private static final int REQUEST_ABOUT_INFO = 5;
	    
	    private static final int DIALOG_ABOUT_INFO = 6;
	    private static final int FILE_DIALOG_REQUEST = 7;
	    
	    
	    public void onActivityResult(int requestCode, int resultCode, Intent data)
		 {
			 Log.d("MAIN", "onActivityResult: requestCode="+requestCode+ ", resultCode=" + resultCode);
			 switch (requestCode)
			 {
			 }
		 }

	private void initShareReference() {
		if (ShareReferenceSaver.getData(this, SERVER_KEY).trim().length() < 1) {
			// this.server_address = "senter-online.cn";
			this.server_address = "49.117.145.10";
		} else {
			this.server_address = ShareReferenceSaver.getData(this, SERVER_KEY);
		}
		if (ShareReferenceSaver.getData(this, PORT_KEY).trim().length() < 1) {
			this.server_port = 10002;
		} else {
			this.server_port = Integer.valueOf(ShareReferenceSaver.getData(
					this, PORT_KEY));
		}
		
		mNFCReaderHelper = new NFCReaderHelper(this, uiHandler);
		mNFCReaderHelper.setServerAddress(this.server_address);
		mNFCReaderHelper.setServerPort(this.server_port);
//		mNFCReaderHelper.read(this);
		
	}

	private void initViews() {
		
//		private TextView tv_info;
//		private TextView nameTextView;
//		private TextView sexTextView;
//		private TextView folkTextView;
//		private TextView birthTextView;
//		private TextView addrTextView;
//		private TextView codeTextView;
//		private TextView policyTextView;
//		private TextView validDateTextView;
//		private TextView dnTextView;
//		private ImageView photoView;
//		private TextView samidTextView;
		
		nameTextView = (TextView) findViewById(R.id.tvName);
		sexTextView = (TextView) findViewById(R.id.tvSex);
		folkTextView = (TextView) findViewById(R.id.tvNation);
		birthTextView = (TextView) findViewById(R.id.tvBornDay);
		addrTextView = (TextView) findViewById(R.id.tvCertAddress);
		codeTextView = (TextView) findViewById(R.id.tvCertNumber);
		policyTextView = (TextView) findViewById(R.id.tvCertOrg);
		validDateTextView = (TextView) findViewById(R.id.tvEffDate);
		//TextView tvExpDate = (TextView) pView.findViewById(R.id.tvExpDate);
		//tvExpDate.setText(bean.expDate);

		photoView = (ImageView) findViewById(R.id.ivPhone);
		tv_info = (TextView) findViewById(R.id.tv_info);
		buttonNFC = (Button) findViewById(R.id.buttonNFC);
		buttonNFC.setVisibility(View.VISIBLE);
		btnSure = (Button) findViewById(R.id.btnSure);

		tv_info.setText("请先点击读卡--->在机器NFC感应区放置身份证");
//		tv_info.setTextColor(Color.rgb(240, 65, 85));
		// readsamtype = (TextView) findViewById(R.id.tv_readsamtype);

		// progressDialog = new ProgressDialog(this);
		// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// progressDialog.setMax(100);
		// progressDialog.setMessage("正在读取信息，请勿移动卡片!");

		buttonNFC.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				readCardNFC();
//				setTitle("信通身份证阅读软件--NFC读卡");

			}
		});
//		buttonOTG.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				readCardOTG();
////				setTitle("信通身份证阅读软件--OTG读卡");
//			}
//		});
		
//		buttonBT.setOnClickListener(new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				if(device == null)
//				{
//					Toast.makeText(MainActivity.this,"请先确认蓝牙是否打开!",Toast.LENGTH_LONG).show();
//				}
//				else
//				{
//					readCardBlueTooth();	
//				}			
//			}
//		});
	}

	/**
	 * NFC 方式读卡
	 */
	protected void readCardNFC() {

		mNFCReaderHelper.read(this);
	}

	/**
	 * OTG方式读卡
	 * 
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	protected void readCardOTG() {
		
	}

	private class NFCReadTask extends AsyncTask<Void, Void, String> {

		private Intent mIntent = null;

		public NFCReadTask(Intent i) {
			mIntent = i;
		}

		@Override
		protected String doInBackground(Void... params) {

			String strCardInfo = mNFCReaderHelper.readCardWithIntent(mIntent);

			return strCardInfo;
		}

		@Override
		protected void onPostExecute(String strCardInfo) {

			if (TextUtils.isEmpty(strCardInfo)) {
				uiHandler.sendEmptyMessage(ConsantHelper.READ_CARD_FAILED);
				nfcTask = null;
				return;
			}

			ObjectMapper objectMapper = new ObjectMapper();
			IdentityCardZ mIdentityCardZ = new IdentityCardZ();

			try {
				mIdentityCardZ = (IdentityCardZ) objectMapper.readValue(
						strCardInfo, IdentityCardZ.class);
			} catch (Exception e) {
				e.printStackTrace();
				nfcTask = null;
				return;
			}
			readCardSuccess(mIdentityCardZ);
//			String strpath = mIdentityCardZ.imagepath;

//			if (strpath != null || strpath.length() > 0) {
//				photoView.setImageBitmap(BitmapFactory.decodeFile(strpath));
//				Log.e(ConsantHelper.STAGE_LOG, "图片成功");
//			}
			
			 try {
			
			 Bitmap bm = BitmapFactory.decodeByteArray(mIdentityCardZ.avatar,
			 0, mIdentityCardZ.avatar.length);
			 DisplayMetrics dm = new DisplayMetrics();
			 getWindowManager().getDefaultDisplay().getMetrics(dm);
			
			 photoView.setMinimumHeight(dm.heightPixels);
			 photoView.setMinimumWidth(dm.widthPixels);
			 photoView.setImageBitmap(bm);
			 Log.e(ConsantHelper.STAGE_LOG, "图片成功");
			 } catch (Exception e) {
			 Log.e(ConsantHelper.STAGE_LOG, "图片失败" + e.getMessage());
			 }
			 
			nfcTask = null;
			super.onPostExecute(strCardInfo);
		}

	}
	
	


	public void resetUI() {
		this.nameTextView.setText("");
		this.sexTextView.setText("");
		this.folkTextView.setText("");
		this.birthTextView.setText("");
		this.codeTextView.setText("");
		this.policyTextView.setText("");
		this.addrTextView.setText("");
		this.validDateTextView.setText("");
		this.tv_info.setText("");
//		dnTextView.setText("");
//		samidTextView.setText("");

		this.photoView.setImageResource(android.R.color.transparent);
	}


	class MyHandler extends Handler {
		private XTNFCActivity activity;

		MyHandler(XTNFCActivity activity) {
			this.activity = activity;
		}

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case ConsantHelper.READ_CARD_SUCCESS:
				buttonNFC.setEnabled(true);
				break;

			case ConsantHelper.SERVER_CANNOT_CONNECT:
				activity.tv_info.setText("服务器连接失败! 请检查网络。");
				buttonNFC.setEnabled(true);
				break;

			case ConsantHelper.READ_CARD_FAILED:
				activity.tv_info.setText("无法读取信息请重试!");
				buttonNFC.setEnabled(true);
				break;

			case ConsantHelper.READ_CARD_WARNING:
				 String str = (String)msg.obj;

                 if(str.indexOf("card")>-1){
                     activity.tv_info.setText("读卡失败: 卡片丢失,或读取错误!");
                 }else{
                     String[] datas = str.split(":");

                     activity.tv_info.setText("网络超时 错误码: "+ Integer.toHexString(new Integer(datas[1])));
                 }
				//activity.tv_info.setText("请移动卡片在合适位置!");
				buttonNFC.setEnabled(true);
				break;

			case ConsantHelper.READ_CARD_PROGRESS:

                int progress_value = (Integer) msg.obj;               				
				activity.tv_info.setText("正在读卡......,进度：" + progress_value + "%");
				break;

			case ConsantHelper.READ_CARD_START:
				activity.resetUI();
				activity.tv_info.setText("开始读卡......");
				break;
			case Error.ERR_CONNECT_SUCCESS:
				String devname = (String) msg.obj;
				activity.tv_info.setText(devname+"连接成功!");
				break;
			case Error.ERR_CONNECT_FAILD:
				String devname1 = (String) msg.obj;
				activity.tv_info.setText(devname1+"连接失败!");
				break;
			case Error.ERR_CLOSE_SUCCESS:
				activity.tv_info.setText((String) msg.obj+"断开连接成功");
				break;
			case Error.ERR_CLOSE_FAILD:
				activity.tv_info.setText((String) msg.obj+"断开连接失败");
				break;
			case Error.RC_SUCCESS:
				String devname12 = (String) msg.obj;
				activity.tv_info.setText(devname12+"连接成功!");
				break;

			}
		}

	}

	private void readCardSuccess(IdentityCardZ identityCard) {

		if (identityCard != null) {
			nameTextView.setText(identityCard.name);
			sexTextView.setText(identityCard.sex);
			folkTextView.setText(identityCard.ethnicity);

			birthTextView.setText(identityCard.birth);
			codeTextView.setText(identityCard.cardNo);
			policyTextView.setText(identityCard.authority);
			addrTextView.setText(identityCard.address);
			validDateTextView.setText(identityCard.period);
		}
		tv_info.setText("读取成功!");
		btnSure.setVisibility(View.VISIBLE);
		resultBean = IdBeanToJson(identityCard);
		Log.e(ConsantHelper.STAGE_LOG, "读卡成功!");
	}
	
	public String IdBeanToJson(IdentityCardZ idbean){
		Map<String,Object> temp = new HashMap<String, Object>();
		if (idbean!=null) {
			
			Bitmap bitmap =  BitmapFactory.decodeByteArray(idbean.avatar, 0, idbean.avatar.length);
			
			ByteArrayOutputStream baos = null;
			
			baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);

			try {
				baos.flush();
				baos.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			

			byte[] bitmapBytes = baos.toByteArray();
			String img = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
			String cust_name = idbean.name;
			String cust_num =idbean.cardNo;
			String cust_add = idbean.address;
			String cust_image = img;
			String cust_born = idbean.birth;
			String cust_nation = idbean.ethnicity;
			String gender = idbean.sex;
			String certOrg = idbean.ethnicity;
//			String effDate= idbean.;
//			String expDate = idbean.expDate;
//			
			cust_image=cust_image.replace("\n", "@");
			temp.put("partyName", cust_name.trim());
			temp.put("certNumber", cust_num.trim());
			temp.put("certAddress", cust_add.trim());
			temp.put("bornDay", cust_born.trim());
			temp.put("nation", cust_nation.trim());
			temp.put("gender", gender.trim());
			temp.put("certOrg", certOrg.trim());
			temp.put("identityPic", cust_image.trim());
//			temp.put("effDate", effDate);
//			temp.put("expDate", expDate);
		}
		JSONObject json = new JSONObject(temp);
		
		return  json.toString();
	}

	public void pageSure(View v){
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		
		
		bundle.putString("result", resultBean);
		Log.e("返回身份证类型", resultBean);
		intent.putExtras(bundle);
		this.setResult(RESULT_OK, intent);//返回页面1
		this.mNFCReaderHelper.disable(this);
		this.finish();

	}
	
	public void goBack(View v){
		this.mNFCReaderHelper.disable(this);
		this.finish();

	}
}
